package com.bjpowernode.validation.validated;

import com.bjpowernode.validation.annotation.Password;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.util.StringUtils;

/**
 *
 */
public class PasswordConstraintValidator implements ConstraintValidator<Password, String> {

    //密码的最小长度
    private int min;

    //密码的最大长度
    private int max;

    @Override
    public void initialize(Password constraintAnnotation) {
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        //验证逻辑：  密码有值就验证6-16位长度，密码没有值就不做验证
        if (StringUtils.hasText(value)) {
            if (value.length() >= min && value.length() <= max) {
                return true; //验证通过
            } else {
                return false; //验证未通过
            }
        } else {
            return true; //没有值，直接验证通过，因为密码可以是空
        }
    }
}
